import 'package:stacked/stacked.dart';
import 'package:vista/shared/models/daily_inspiration.dart';
import 'package:vista/shared/models/user_frame.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/daily_inspiration_service.dart';
import 'package:vista/shared/services/relation_bond.dart';

/// 每日灵感详情视图模型
/// 管理每日灵感详情页面的数据和状态
class InspirationDetailViewModel extends BaseViewModel {
  final AuthFocus _authFocus;
  final DailyInspirationService _dailyInspirationService;
  final RelationBond _relationBond;
  final String inspirationId;

  InspirationDetailViewModel(
    this._authFocus,
    this._dailyInspirationService,
    this._relationBond,
    this.inspirationId,
  );

  DailyInspiration? _inspiration;
  DailyInspiration? get inspiration => _inspiration;

  UserFrame? _author;
  UserFrame? get author => _author;

  UserFrame? _currentUser;
  UserFrame? get currentUser => _currentUser;

  bool _isFollowing = false;
  bool get isFollowing => _isFollowing;

  /// 初始化数据
  Future<void> initialize() async {
    setBusy(true);
    try {
      _currentUser = await _authFocus.getCurrentUser();
      await _loadInspiration();
      await _loadAuthor();
      await _checkFollowingStatus();
    } finally {
      setBusy(false);
    }
  }

  /// 加载灵感数据
  Future<void> _loadInspiration() async {
    _inspiration = await _dailyInspirationService.getInspirationById(
      inspirationId,
    );
    notifyListeners();
  }

  /// 加载发布者信息
  Future<void> _loadAuthor() async {
    if (_inspiration == null) return;

    final allUsers = await _authFocus.getUsers();
    _author = allUsers.firstWhere(
      (user) => user.id == _inspiration!.authorId,
      orElse: () => allUsers.first,
    );
    notifyListeners();
  }

  /// 检查是否已关注
  Future<void> _checkFollowingStatus() async {
    if (_currentUser == null || _author == null) {
      _isFollowing = false;
      notifyListeners();
      return;
    }

    _isFollowing = await _relationBond.isFollowing(
      followerId: _currentUser!.id,
      followingId: _author!.id,
    );
    notifyListeners();
  }

  /// 关注/取消关注用户
  Future<void> toggleFollow() async {
    if (_currentUser == null || _author == null) return;

    if (_isFollowing) {
      await _relationBond.unfollowUser(
        followerId: _currentUser!.id,
        followingId: _author!.id,
      );
    } else {
      await _relationBond.followUser(
        followerId: _currentUser!.id,
        followingId: _author!.id,
      );
    }

    await _checkFollowingStatus();
  }
}
